/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sistcomptf;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;




/**
 *
 * @author Medina
 */
public class Saver implements Runnable{
    private DataOutputStream odbc;
    private Comunicador comunicador;
    private FileWriter fWriter;
    private BufferedWriter bWriter;


    public Saver(Comunicador comunicador){
        try {
            this.comunicador = comunicador;
            fWriter = new FileWriter("ODBC.txt", false);
            fWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(Saver.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    
    
    public void saveODBC(int tempActual){
        try {
            fWriter = new FileWriter("ODBC.txt", true);
            bWriter = new BufferedWriter(fWriter);
            
            //System.out.println("saving"+tempActual);
            
            bWriter.write(String.valueOf(tempActual));
            bWriter.newLine();
     
            closeODBC();
        } catch (IOException ex) {
            Logger.getLogger(Saver.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    }
    
    public void closeODBC(){
        try {
             bWriter.close();
             fWriter.close();

        } catch (IOException ex) {
            Logger.getLogger(Saver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void getDataODBC(){

        Integer recv = comunicador.getDato();
        
        Integer ACK=128;
        Byte recvB;
        
        System.out.println(recv);
        if(recv!=-1){
            if((recv & ACK) ==128 ){
                //Esto es un ACK de control
                System.out.println("---ACK "+recv.toBinaryString(recv));
                comunicador.informarError(recv);
            }
            else{
                //Entonces es un dato de temperatura
                saveODBC(recv);
            }
        
        }
        
    }

    public void run() {
        while(true){
            getDataODBC();
           
        }
    }
}
